{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-1-88a9fb60e680>:7: read_data_sets (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n",
      "WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:260: maybe_download (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please write your own downloading logic.\n",
      "WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/base.py:252: _internal_retry.<locals>.wrap.<locals>.wrapped_fn (from tensorflow.contrib.learn.python.learn.datasets.base) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use urllib or similar directly.\n",
      "Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.\n",
      "WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:262: extract_images (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-images-idx3-ubyte.gz\n",
      "Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.\n",
      "WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:267: extract_labels (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.data to implement this functionality.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/train-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:110: dense_to_one_hot (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use tf.one_hot on tensors.\n",
      "Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-images-idx3-ubyte.gz\n",
      "Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.\n",
      "Extracting /tmp/tensorflow/mnist/input_data/t10k-labels-idx1-ubyte.gz\n",
      "WARNING:tensorflow:From /anaconda3/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/datasets/mnist.py:290: DataSet.__init__ (from tensorflow.contrib.learn.python.learn.datasets.mnist) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use alternatives such as official/mnist/dataset.py from tensorflow/models.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "# 载入数据集\n",
    "# Import data\n",
    "data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "\n",
    "# 每个批次送100张图片\n",
    "batch_size = 100\n",
    "# 计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples // batch_size"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "y = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "W1 = tf.Variable(tf.truncated_normal([784, 500], stddev=0.1), name='W1') #第一个隐层，500个神经元\n",
    "b1 = tf.Variable(tf.zeros([500]) + 0.1, name='b1')\n",
    "L1 = tf.nn.tanh(tf.matmul(x, W1) + b1, name='L1')\n",
    "\n",
    "W2 = tf.Variable(tf.truncated_normal([500, 300], stddev=0.1), name='W2') #第二个隐层，300个神经元\n",
    "b2 = tf.Variable(tf.zeros([300]) + 0.1, name='b2')\n",
    "L2 = tf.nn.tanh(tf.matmul(L1, W2) + b2, name='L2')\n",
    "\n",
    "W3 = tf.Variable(tf.truncated_normal([300, 10], stddev=0.1), name='W3')\n",
    "b3 = tf.Variable(tf.zeros([10]) + 0.1, name='b3')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "#prediction = tf.nn.softmax(tf.matmul(L2, W3) + b3)\n",
    "prediction = tf.matmul(L2, W3) + b3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-17-e87fa2348815>:2: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See @{tf.nn.softmax_cross_entropy_with_logits_v2}.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "#loss = tf.reduce_mean(tf.square(y - prediction))\n",
    "cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))·"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "learning_rate = 0.2\n",
    "optimizer =  tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)\n",
    "\n",
    "# 结果存放在一个布尔型列表中\n",
    "correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))  \n",
    "\n",
    "# 求准确率\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Iter0, Testing accuracy:0.9529\n",
      "Iter2, Testing accuracy:0.9708\n",
      "Iter4, Testing accuracy:0.9762\n",
      "Iter6, Testing accuracy:0.9775\n",
      "Iter8, Testing accuracy:0.9794\n",
      "Iter10, Testing accuracy:0.98\n",
      "Iter12, Testing accuracy:0.9805\n",
      "Iter14, Testing accuracy:0.98\n",
      "Iter16, Testing accuracy:0.9818\n",
      "Iter18, Testing accuracy:0.9811\n",
      "Iter20, Testing accuracy:0.9814\n",
      "Iter22, Testing accuracy:0.9818\n",
      "Iter24, Testing accuracy:0.9819\n",
      "Iter26, Testing accuracy:0.9811\n",
      "Iter28, Testing accuracy:0.982\n",
      "Iter30, Testing accuracy:0.9818\n",
      "Iter32, Testing accuracy:0.9823\n",
      "Iter34, Testing accuracy:0.9819\n",
      "Iter36, Testing accuracy:0.9821\n",
      "Iter38, Testing accuracy:0.982\n",
      "Iter40, Testing accuracy:0.9822\n",
      "Iter42, Testing accuracy:0.9821\n",
      "Iter44, Testing accuracy:0.9826\n",
      "Iter46, Testing accuracy:0.9823\n",
      "Iter48, Testing accuracy:0.982\n"
     ]
    }
   ],
   "source": [
    "init = tf.global_variables_initializer()\n",
    "\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init)\n",
    "    for epoch in range(50):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n",
    "            sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys})\n",
    "\n",
    "        test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})\n",
    "\n",
    "        if epoch % 2 == 0:\n",
    "            print(\"Iter\" + str(epoch) + \", Testing accuracy:\" + str(test_acc))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
